class CustomError extends Error{
    constructor(data = {}) {
        super()
        this.name = "CustomError"; //错误类型
        this.actionName = "";
        this.errMsg = ""; //错误信息
        this.errCode = ""; //错误编码
        this._reset(data);
    }
    /*
    * 重置错误数据
    * */
    _reset (data) {
        let currentActionName = this.actionName;
        let actionName = data.actionName;
        if (this._isType("Object")(data)) {
            let error = data.error;
            Object.assign(this, data);
            if (error) { // error对象存在
                switch (true) {
                    case this._isType("Object")(error): //普通对象实例
                        Object.assign(this, error);
                        break
                    case this._isType("Error")(error):  //Error对象实例
                        error.actionName ? actionName = error.actionName : null;
                        this.name = error.name + " | " + this.name;
                        this.errMsg = error.message || error.errMsg || this.errMsg;
                        this.errCode = error.errorCode || error.errCode || this.errCode; //错误编码
                        this.stack = error.stack;
                        break
                    default:
                        this.errMsg = error
                        break
                }
            }
        } else if (this._isType("Error")(data)) {
            this.name = data.name + " | " + this.name;
            this.errMsg = data.message || data.errMsg || this.errMsg;
            this.errCode = data.errorCode || data.errCode || this.errCode; //错误编码
            this.stack = data.stack;
        } else {
            this.errMsg = data
        }
        this.actionName = actionName ? (currentActionName ? actionName + " ---> " + currentActionName : "") : currentActionName;
    }
    /*
    * 类型检测
    * */
    _isType (type) {
        return function (data) {
            return Object.prototype.toString.call(data) === "[object " + type + "]"
        }
    }

    /*
    * 对象解析
    * */
    parse () { //返回对象
        return {
            name: this.name,
            actionName: this.actionName,
            errMsg: this.errMsg,
            errCode: this.errCode
        }
    }
}

module.exports = CustomError